package com.car.rental.order.controller;

import com.car.rental.common.core.response.ResponseResult;
import com.car.rental.order.dto.PaymentDTO;
import com.car.rental.order.service.AlipayService;
import com.car.rental.order.service.PaymentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import com.car.rental.order.entity.PaymentRecord;
import com.car.rental.common.core.exception.BusinessException;
import com.car.rental.common.utils.JsonUtils;

import javax.validation.Valid;
import java.util.Map;
import java.util.HashMap;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/payment")
@RequiredArgsConstructor
public class PaymentController {

    private final PaymentService paymentService;
    private final AlipayService alipayService;

    @PostMapping
    public ResponseResult<Map<String, String>> createPayment(
            @RequestAttribute("userId") Long userId,
            @Valid @RequestBody PaymentDTO paymentDTO) {
        // 1. 创建支付记录
        ResponseResult<String> paymentResult = paymentService.createPayment(userId, paymentDTO);
        
        // 2. 根据支付方式处理
        if ("ALIPAY".equals(paymentDTO.getPaymentMethod())) {
            // 获取支付记录
            PaymentRecord payment = paymentService.getByPaymentNo(paymentResult.getData());
            // 创建支付宝支付
            ResponseResult<String> alipayResult = alipayService.createPayment(payment);
            
            Map<String, String> response = new HashMap<>();
            response.put("paymentNo", payment.getPaymentNo());
            response.put("form", alipayResult.getData());
            return ResponseResult.success(response);
        }
        
        throw new BusinessException("不支持的支付方式");
    }

    @GetMapping("/status/{orderNo}")
    public ResponseResult<Integer> getPaymentStatus(@PathVariable String orderNo) {
        return paymentService.getPaymentStatus(orderNo);
    }

    // 支付回调接口（实际项目中需要验证签名等）
    @PostMapping("/callback/{paymentNo}")
    public ResponseResult<Void> paymentCallback(
            @PathVariable String paymentNo,
            @RequestParam Integer status,
            @RequestParam(required = false) String reason) {
        if (status == 1) {
            return paymentService.paymentSuccess(paymentNo);
        } else {
            return paymentService.paymentFailed(paymentNo, reason);
        }
    }

    /**
     * 支付宝异步通知接口
     */
    @PostMapping("/alipay/notify")
    public String alipayNotify(@RequestParam Map<String, String> params) {
        try {
            log.info("收到支付宝回调通知：{}", params);
            alipayService.handleCallback(params);
            return "success";
        } catch (Exception e) {
            log.error("支付宝回调处理失败", e);
            return "fail";
        }
    }

    /**
     * 查询支付状态
     */
    @GetMapping("/query/{paymentNo}")
    public ResponseResult<Boolean> queryPaymentStatus(@PathVariable String paymentNo) {
        return alipayService.queryPaymentStatus(paymentNo);
    }
} 